package cn.xo68.ide.plugin.common.jobs;

import cn.xo68.ide.plugin.common.domain.CodeGenerateInfo;
import cn.xo68.ide.plugin.common.job.JobCallback;
import cn.xo68.ide.plugin.common.job.JobCallbackAdapter;
import cn.xo68.ide.plugin.common.job.ToolSuiteJob;
import cn.xo68.ide.plugin.common.service.CodeGenerateManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.vfs.VirtualFile;
import com.wy2.generator.database.entity.DatabaseTable;

import java.util.LinkedList;

/**
 * 保存代码生成模块信息
 * @author  wuxie
 */
public class SaveCodeGenerateInfoJob implements ToolSuiteJob {
    private final String title;
    private final JobCallback jobCallback;
    private final VirtualFile virtualFile;
    private final CodeGenerateInfo codeGenerateInfo;
    private final LinkedList<DatabaseTable> tables;

    public SaveCodeGenerateInfoJob(String title, VirtualFile virtualFile, CodeGenerateInfo codeGenerateInfo, LinkedList<DatabaseTable> tables) {
        this.title = title;
        this.virtualFile = virtualFile;
        this.codeGenerateInfo = codeGenerateInfo;
        this.tables = tables;
        this.jobCallback= new JobCallbackAdapter(this.title);
    }

    @Override
    public String getTitle() {
        return title;
    }

    @Override
    public boolean isModal() {
        return false;
    }

    @Override
    public boolean isStartInBackground() {
        return true;
    }

    @Override
    public JobCallback getCallback() {
        return jobCallback;
    }

    @Override
    public void execute(ProgressIndicator indicator) throws Exception {

        CodeGenerateManager codeGenerateManager = CodeGenerateManager.getInstance();
        CodeGenerateInfo oldCodeGenerateInfo=codeGenerateManager.loadCodeGenerateInfo(virtualFile);
        if(oldCodeGenerateInfo!=null) {
            for (String generateTable : oldCodeGenerateInfo.getGeneratedTables()) {
                codeGenerateInfo.addGeneratedTable(generateTable);
            }
        }
        for (DatabaseTable databaseTable : this.tables) {
            codeGenerateInfo.addGeneratedTable(databaseTable.getSqlName());
        }
        codeGenerateManager.saveCodeGenerateInfo(virtualFile,codeGenerateInfo);
    }
}
